#import "BWSearchArrayController.h"

@implementation BWSearchArrayController

- (BOOL) string: (NSString *) search
       inString: (NSString *) string
{
    BOOL found = NO;

    // see if the name matches the search string
    NSRange range;
    range = [string rangeOfString: search
                    options: NSCaseInsensitiveSearch];

    // found the search string in the name, add it to
    // the result set
    if (range.location != NSNotFound) {
        found = YES;
    }

    return (found);

} // string


// returns an array containing the content of the objects arranged
// with the user's critera entered into the search box thingie

- (NSArray *) arrangeObjects: (NSArray *) objects
{
    // result of the filtering
    NSArray *returnObjects = objects;

    // if there is a search string, use it to compare with the
    // search field string

    if (searchString != nil) {

        // where to store the filtered 
        NSMutableArray *filteredObjects;
        filteredObjects = [NSMutableArray arrayWithCapacity: [objects count]];

        // walk the enumerator 
        NSEnumerator *enumerator = [objects objectEnumerator];

        id item; // actully BWThreadColors
        while (item = [enumerator nextObject]) {
            NSArray *paths = [self keyPathsToSearch];

            NSEnumerator *pathEnumerator = [paths objectEnumerator];

            NSString *path;
            while (path = [pathEnumerator nextObject]) {
                NSString *string;
                string = [item valueForKeyPath: path];
                
                if ([self string: searchString
                          inString: string]) {
                    [filteredObjects addObject: item];
                    break;
                }
            }
        }

        returnObjects = filteredObjects;
    }

    return ([super arrangeObjects: returnObjects]);

} // arrangeObjets



// called by the search box

- (void) setSearchString: (NSString *) string
{
    [searchString release];

    if ([string length] == 0) {
        searchString = nil;
    } else {
        searchString = [string copy];
    }

} // setSearchString



// called by the search box too

- (void) search: (id) sender
{
    [self setSearchString: [sender stringValue]];
    [self rearrangeObjects];

} // search

@end // BWSearchArrayController

